package com.fan.admin.service.impl;

import com.fan.admin.dao.CourseMapper;
import com.fan.admin.service.CourseService;
import com.fan.admin.service.TeacherService;
import com.fan.commons.pojo.Course;
import com.fan.commons.pojo.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;


/**
 * @author fan
 * @date 2021/2/24
 */
@Service
public class CourseServiceImpl implements CourseService {

	@Autowired
	private CourseMapper courseMapper;

	@Autowired
	private TeacherService teacherService;

	@Override
	public int addCourse(Course course) {
		List<Teacher> teachers = teacherService.queryTeachers(new Teacher().setTeacherId(course.getTeacherId()));
		if (teachers.size() != 1) {
			return 0;
		}
		Teacher teacher = teachers.get(0);
		String courseId = UUID.randomUUID().toString().substring(0, 8);
		course.setCourseId(courseId);
		course.setCollegeId(teacher.getCollegeId());
		course.setSystemId(teacher.getSystemId());
		course.setRestNumber(course.getNumber());
		course.setRestNumber(course.getNumber());
		course.setVersion("" + System.currentTimeMillis());
		return courseMapper.insertCourseMust(course);
	}

	@Override
	public int deleteCourseById(Integer id) {
		return courseMapper.deleteCourseById(id);
	}

	@Override
	public int updateCourse(Course course) {
		List<Teacher> teachers = teacherService.queryTeachers(new Teacher().setTeacherId(course.getTeacherId()));
		if (teachers.size() != 1) {
			return 0;
		}
		Teacher teacher = teachers.get(0);
		course.setCollegeId(teacher.getCollegeId());
		course.setSystemId(teacher.getSystemId());
		course.setNewVersion("" + System.currentTimeMillis());
		if (course.getNature() == 1) {
			// 已被选的数据条数比较
			Course temp = courseMapper.queryCourseById(course.getId());
			int oldNum = temp.getNumber() - temp.getRestNumber();
			int newNum = course.getNumber() - course.getRestNumber();
			if (oldNum > newNum) {
				return 0;
			}
		}
		return courseMapper.updateCourse(course);
	}

	@Override
	public List<Course> queryCourse() {
		return courseMapper.queryCourse();
	}

	@Override
	public Course queryCourseById(Integer id) {
		return courseMapper.queryCourseById(id);
	}

	@Override
	public Course queryCourseByCourseId(String courseId) {
		return courseMapper.queryCourseByCourseId(courseId);
	}

	@Override
	public List<Course> queryCourseByNature(Integer nature) {
		return courseMapper.queryCourseByNature(nature);
	}

	@Override
	public List<Course> queryCourseActive(Course course) {
		return courseMapper.queryCourseActive(course);
	}

	@Override
	public int updateCourseScore(Course course) {
		course.setNewVersion("" + System.currentTimeMillis());
		return courseMapper.updateCourse(course);
	}
}
